List PatternsĀ¶
This demonstrates the mapping pattern.
Map is a mathematical term that means going from one value to a corresponding value.
This is also referred to as the transform pattern.
šØš¼āšØ smaller_numbers.py
Ā¶
Write a function that creates a new list where each item has been divided by 2.
You can pass lists to functions and return lists from functions.
This demonstrates the filter pattern.
A new collection is created with certain items filtered out.
This demonstrates the selection pattern.
A single item is selected from a collection.
This demonstrates the accumulator pattern.
total
accumulates the values in the collection.
Another way for list patternsĀ¶
InĀ [23]:
numbers = [1, 2, 3, 4, 5]
min
, max
Ā¶
InĀ [4]:
min(numbers), max(numbers)
Out[4]:
(1, 5)
sum
Ā¶
InĀ [2]:
sum(numbers)
Out[2]:
15
InĀ [3]:
sum(numbers) / len(numbers)
Out[3]:
3.0
List comprehensionsĀ¶
Mapping patternĀ¶
InĀ [5]:
new_numbers = []
for number in numbers:
new_number = number + 7
new_numbers.append(new_number)
new_numbers
Out[5]:
[8, 9, 10, 11, 12]
InĀ [6]:
new_numbers = [number + 7 for number in numbers]
new_numbers
Out[6]:
[8, 9, 10, 11, 12]
InĀ [7]:
def add_seven(number):
return number + 7
new_numbers = [add_seven(number) for number in numbers]
new_numbers
Out[7]:
[8, 9, 10, 11, 12]
InĀ [10]:
[number // 3 for number in numbers]
Out[10]:
[0, 0, 1, 1, 1]
InĀ [11]:
[number ** 2 for number in numbers]
Out[11]:
[1, 4, 9, 16, 25]
InĀ [12]:
[number ** 0.5 for number in numbers]
Out[12]:
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]
Filter patternĀ¶
InĀ [13]:
new_numbers = []
for number in numbers:
if number > 3:
new_numbers.append(number)
new_numbers
Out[13]:
[4, 5]
InĀ [14]:
numbers = [1, 2, 3, 4, 5]
InĀ [18]:
[number for number in numbers if number > 3]
Out[18]:
[4, 5]
InĀ [19]:
[number for number in numbers if number % 2 == 0]
Out[19]:
[2, 4]
InĀ [20]:
[number for number in numbers if number * 5 < 20]
Out[20]:
[1, 2, 3]
All Together with comprehensionsĀ¶
InĀ [22]:
nums = [0, 7, 2, 14, 20, 32, 5, 12]
# subtract 7
nums = [number - 7 for number in nums]
# Keep 0 <= num <= 10
def is_keeper(number):
return 0 <= number <= 10
nums = [number for number in nums if is_keeper(number)]
print(nums)
[0, 7, 5]
InĀ [21]:
nums = [0, 7, 2, 14, 20, 32, 5, 12]
[number - 7 for number in nums if 0 <= number - 7 < 10]
Out[21]:
[0, 7, 5]
Key IdeasĀ¶
- mapping pattern
- filter pattern
- selection pattern
- accumulator pattern
- List comprehensions
- mapping pattern
- filter pattern